#include "item.h"
#include "manager.h"
#include "monster.h"
#include "tile.h"

using std::string;

int Item::itemCounter_ = 0;

Item::Item( int x, int y, string name, char symbol ) : MapObject( -1, -1, ( name + numToString( itemCounter_ ) ), symbol )
{
	setPos( x, y );
	owner_ = nullptr;
	manager.getMItems().push_back( this );
	itemCounter_++;
	type_.item = 1;
}

Item::Item() : MapObject( -1, -1, ( name + numToString( itemCounter_ ) ), symbol )
{
	owner_ = nullptr;
	manager.getMItems().push_back( this );
	itemCounter_++;
	type_.item = 1;
}

Item::~Item()
{
	setPos( -1, -1 );
	manager.getMItems().remove( this );
}

int Item::setPos( int x, int y )
{
	Tile * prevLoc = tileAt( this->x, this->y );
	if( MapObject::setPos( x, y ) )
	{
		if( prevLoc != nullptr )
		{
			auto iter = prevLoc->itemContents.begin();
			for( iter; iter != prevLoc->itemContents.end(); iter++ )
			{
				if( ( *iter ) == this )
				{
					prevLoc->itemContents.erase( iter );
					break;
				}
			}
		}
		Tile * newLoc = tileAt( this->x, this->y );
		if( newLoc != nullptr )
		{
			newLoc->itemContents.push_back( this );
		}
		return 1;
		
	}
	else
		return 0;
}

Monster * Item::getOwner() const
{
	return owner_;
}

void Item::setOwner( Monster * newOwner )
{
	owner_ = newOwner;
}